﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using SCS.Core.Models.ModelsFontend;

namespace SCS.Core.Controllers
{
    public class ProductController : BaseFontendController
    {
                
        #region "TypeProduct"

        public ActionResult TypeProductDetail(int id)
        {
            IntPage();
            SCSService.Type_Product type = Models.ModelsFontend.ProductModel.GetTypeProductByIdAndSiteGuid(id, DefaultSiteGuidGetter()) != null ? Models.ModelsFontend.ProductModel.GetTypeProductByIdAndSiteGuid(id, DefaultSiteGuidGetter()) : new SCSService.Type_Product();
            ViewData["IDTypeProduct"] = id;
            return View(type);
        }

        //public StringBuilder GetListTypeProductBuilder(int? id)
        //{
        //    StringBuilder sb = new StringBuilder();
        //    int siteGuid=GetSiteGuid();
            
        //    return ListTypeProductBuilder(ref sb, id,siteGuid);
        //}

        //public StringBuilder ListTypeProductBuilder(ref StringBuilder sb, int? id,int siteGuid)
        //{
        //    int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
        //    List<SCSService.Type_Product> listType = Models.ModelsFontend.ProductModel.GetListTypeProductByParentId(id, LanguageID, siteGuid);
        //    sb.Append("<ul>");
        //    foreach (var item in listType)
        //    {
        //        if (DefaultHostGetter().Contains("localhost"))
        //        {
        //            sb.Append("<li><a href='/" + siteGuid + "/" + DefaultLanguageGetter() + "/Product/ListProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
        //        }
        //        else
        //        {
        //            sb.Append("<li><a href='/" + DefaultLanguageGetter() + "/Product/ListProduct/" + item.TypeProductID + "'>" + item.TypeProductName + "</a>");
        //        }
                
        //        List<SCSService.Type_Product> listChild = Models.ModelsFontend.ProductModel.GetListTypeProductByParentId(item.TypeProductID,LanguageID, siteGuid);
        //        if (listChild.Count() > 0)
        //        {
        //            ListTypeProductBuilder(ref sb, item.TypeProductID,siteGuid);
        //        }
        //        sb.Append("</li>");
        //    }
        //    sb.Append("</ul>");

        //    return sb;
        //}

        //[ChildActionOnly]
        //public ActionResult MenuTypeProduct()
        //{
        //    int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
        //    int siteGuid = GetSiteGuid();

        //    ViewData["MenuTypeProduct"] = GetListTypeProductBuilder(null);

        //    ///return ket qua la 1 childAction tai 1 folder khac
        //    return PartialView("../BaseFontend/" + siteGuid + "/MenuTypeProduct");

        //}

        #endregion

        
        #region "Product"

        public ActionResult ProductDetail(int? id)
        {
            IntPage();           
            return View();
        }

        [ChildActionOnly]
        public ActionResult ProductView(int? id)
        {
            SCSService.Product product = Models.ModelsFontend.ProductModel.GetProductByIDAndSiteGuid(id??0, DefaultSiteGuidGetter()) != null ? Models.ModelsFontend.ProductModel.GetProductByIDAndSiteGuid(id??0, DefaultSiteGuidGetter()) : new SCSService.Product();

            ViewData["IDProduct"] = id;
            int? LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int? currencyID = null;
            int idType = 0;
            List<Product> listAnother=new List<Product>();

            if (GetPriceProduct(id??0, LanguageID, currencyID) != null)
            {
                if (GetPriceProduct(id??0, LanguageID, currencyID).PriceValue != null && GetPriceProduct(id??0, LanguageID, currencyID).CurrencyID != null)
                    ViewData["PriceProduct"] = String.Format("{0:N0}", GetPriceProduct(id??0, LanguageID, currencyID).PriceValue.ToString() + " " + StockModel.GetCurrencyByID((int)GetPriceProduct(id??0, LanguageID, currencyID).CurrencyID).CurrencyCode);
                else
                    ViewData["PriceProduct"] = string.Empty;
            }
            else
                ViewData["PriceProduct"] = string.Empty;

            if (GetStockProduct(id??0) != null)
            {
                if (GetStockProduct(id??0) != null)
                {
                    ViewData["StockProduct"] = GetStockProduct(id??0) > 0 ? GetStockProduct(id??0).ToString() : "Hết hàng";
                }
                else
                    ViewData["StockProduct"] = "";
            }
            else
                ViewData["StockProduct"] = string.Empty;

            //List cac thuoc tinh cua san pham (list type Properties)
            string viewName = "";
            List<Type_Property> listTypeProperties=Models.ModelsFontend.ProductModel.GetListTypePropertiesByProductID(id??0,LanguageID??0,1);

            if (listTypeProperties.Count() > 0)
            {
                ViewData["listTypeProperties"] = listTypeProperties;
                foreach (var item in listTypeProperties)
                {
                    if (item.TypePropertiesAbstract != null && item.TypePropertiesAbstract != string.Empty)
                    {
                        viewName = item.TypePropertiesAbstract;
                        if (item.TypePropertiesAbstract == "property_comment")
                        {
                            if(Models.ModelsFontend.ProductModel.GetListProductProperties(item.TypePropertiesID, id).Count > 0)
                            {
                                ViewData["property_comment"] =  Models.ModelsFontend.ProductModel.GetListProductProperties(item.TypePropertiesID, id);
                            }
                            else
                            {
                                ViewData["property_comment"]= "Not comment";
                            }
                            
                        }
                        else
                        {
                            ViewData[viewName] = Models.ModelsFontend.ProductModel.GetListProductProperties(item.TypePropertiesID, id);
                        }
                        
                    }
                }
            }

            // cac san pham cung danh muc
            string[] arr;
            string urlOld = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : "";
            if (urlOld != "" && (urlOld.Contains("/ListProduct") || urlOld.Contains("/listproduct")))
            {
                arr = urlOld.Split('/');
                if (arr[arr.Length - 1].Contains("ListProduct") != false && arr[arr.Length - 1].Contains("listproduct") != false)
                {
                    idType = int.Parse(arr[arr.Length - 1].Contains('?') != false ? arr[arr.Length - 1] : arr[arr.Length - 1].Substring(0, arr[arr.Length - 1].IndexOf('?')));
                }
                else
                {
                    var listTypes = Models.ModelsFontend.ProductModel.ListTypeProductIDManagerByProductID(id ?? 0);
                    foreach (var it in listTypes)
                    {
                        if (Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1).Count > 1)
                        {
                            listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                            int count = listAnother.Count();
                            int index = new Random().Next(count);
                            if (count > 6)
                                listAnother = listAnother.Where(p => p.ProductID != id).Skip(index).Take(5).ToList();
                            else
                                listAnother = listAnother.Where(p => p.ProductID != id).Skip(index).Take(count).ToList();

                            
                            break;
                        }
                        else
                            listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                    }
                }
            }
            else
            {
                var listTypes = Models.ModelsFontend.ProductModel.ListTypeProductIDManagerByProductID(id??0);
                foreach (var it in listTypes)
                {
                    if (Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1).Count > 1)
                    {
                        listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                        int count = listAnother.Count();
                        int index = new Random().Next(count);

                        if (count > 6)
                            listAnother = listAnother.Where(p => p.ProductID != id).Skip(index).Take(5).ToList();
                        else
                            listAnother = listAnother.Where(p => p.ProductID != id).Skip(index).Take(count).ToList();


                        break;
                    }
                    else
                        listAnother = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(it, (int)LanguageID, GetSiteGuid(), 1);
                }
            }
            
            
            
            ViewData["listAnother"] = listAnother;
            ViewData["idParent"] = idType;

            //return View(product);
            return PartialView("../BaseFontend/" + GetSiteGuid() + "/ProductView", product);
        }

        public Product_Price GetPriceProduct(int id, int? languageId,int? currencyID)
        {
            return Models.ModelsFontend.ProductModel.GetProductPriceByProductId(id, languageId,currencyID);
        }

        public long GetStockProduct(int id)
        {
            return Models.ModelsFontend.ProductModel.GetProductStockByProductId(id);
        }

        
        public ActionResult ListProduct(int? id,string typeList)
        {
            IntPage();
            return View();
        }

        public ActionResult TestList(int? id)
        {
            IntPage();
            return View();
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProducts(int? id, string typeList)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 9;

            if (typeList == null || typeList==string.Empty)
            {
                ViewData["typeList"] = "list";
                typeList = "list";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            ViewData["idList"] = id;
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            return ListProducts(currentPage, pageSize, null, id,typeList);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProducts(int? currentPage, int? pageSize, string gridAction, int? id, string typeList)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid =GetSiteGuid();

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "list";
                typeList = "list";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            //ViewData["ListTypeProduct"] = GetListTypeProductBuilder(null);

            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 9;
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.ModelsFontend.ProductModel.GetListProductByTypeProduct(id, LanguageID, siteGuid,1).AsQueryable();
            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize,null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            ViewData["idList"] = id;
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var list = cart.GetListCartItemByCartID();
            ShoppingCart shopcart = new ShoppingCart();

            ViewData["cart"] = list;

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProducts", new List<SCSService.Product>());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProducts", result);
        }

        public ActionResult CreateWebshop(int? id)
        {
            return View();
        }

        [ChildActionOnly]
        public ActionResult MenuFilter(int? typeId)
        {
            int LanguageID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();
            List<SCSService.Type_Property> listFilter = Models.ModelsFontend.ProductModel.GetListFilterForTypeProduct(typeId, LanguageID, GetSiteGuid());

            ViewData["MenuFilter"] = listFilter;

            ///return ket qua la 1 childAction tai 1 folder khac
            return PartialView("../BaseFontend/" + siteGuid + "/MenuFilter");

        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListProductsFilters(int? id, string typeList, string listType)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 9;

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            ViewData["idList"] = id;
            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            return ListProductsFilters(currentPage, pageSize, null, id, typeList, listType);
        }

        [ChildActionOnly]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ListProductsFilters(int? currentPage, int? pageSize, string gridAction, int? id, string typeList,string listType)
        {
           
            List<Type_Property> listFilter = new List<Type_Property>();
            if (listType != string.Empty && listType != null)
            {
                if (listType.Contains(','))
                {
                    var arrID = listType.Split(',');
                    foreach (var item in arrID)
                    {
                        Type_Property ty = Models.StockModel.GetTypePropertiesById(int.Parse(item));
                        listFilter.Add(ty);
                    }
                }
                else
                {
                    Type_Property ty = Models.StockModel.GetTypePropertiesById(int.Parse(listType));
                    listFilter.Add(ty);
                }
                
            }
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            if (typeList == null || typeList == string.Empty)
            {
                ViewData["typeList"] = "grid";
                typeList = "grid";
            }
            else
            {
                ViewData["typeList"] = typeList;
            }
            //ViewData["ListTypeProduct"] = GetListTypeProductBuilder(null);

            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 9;
            }

            ViewData["currentPage"] = currentPage;

            var query = Models.ModelsFontend.ProductModel.GetListProductByTypeProductFilter(id, LanguageID, siteGuid, 1,listFilter).AsQueryable();
            int totalRows = query.Count();

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize, null);

            var result = query.ToList();

            if (query.Count() > 0)
            {

            }

            ViewData["idList"] = id;
            var cart = ShoppingCart.GetCart(this.HttpContext);
            var list = cart.GetListCartItemByCartID();
            ShoppingCart shopcart = new ShoppingCart();

            ViewData["cart"] = list;

            if (totalRows == 0)
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductsFilters", new List<SCSService.Product>());
            else
                return PartialView("../BaseFontend/" + GetSiteGuid() + "/ListProductsFilters", result);
        }
        #endregion

        
    }
}
